<?php

use TbfExcel\ExcelData;
/**
 * 导入导出excel
 * 需要引入PHPExcel这个包
 */
class TbfExcel {
    static function fromString($content){
        $file = TbfConfig::$TmpPath.'/Excel/'.TbfRand::randLetterNumber(10).'.xlsx';
        TbfFile::writeFile($file,$content);
        $data = self::fromFile($file);
        TbfFile::deleteFile($file);
        return $data;
    }

    /**
     * 从文件名读入excel
     * @return ExcelData
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    static function fromFile($filePath){
        class_exists('PHPExcel');
        $inputFileType = PHPExcel_IOFactory::identify($filePath);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $arr_data = array();
        //  Load $inputFileName to a PHPExcel Object
        /** @var \PHPExcel $objPHPExcel */
        $objPHPExcel  = $objReader->load($filePath);
        $objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
        for ($row = 1; $row <= $highestRow; ++$row) {
            for ($col = 0; $col < $highestColumnIndex; ++$col) {
                $value=(string)$objWorksheet->getCellByColumnAndRow($col, $row);
                $arr_data[$row-1][$col]=$value;
            }
        }
        $data = self::Trim2DArray($arr_data);
        if (empty($data)){
            return array();
        }
        return ExcelData::from2D($data);
    }

    /**
     * 从http上传的文件读入excel
     * @return ExcelData
     */
    static function mustFromInput(){
        if (empty($_FILES['file']['tmp_name'])){
            TbfError::client('Please choose a file to upload.');
            return null;
        }
        return self::fromFile($_FILES['file']['tmp_name']);
    }
    static function toFile($filePath,ExcelData $excelData){
        $data = $excelData->to2D();
        $xls = new \PHPExcel();
        $sheet = $xls->getActiveSheet();
        for($i=0;$i<count($data);$i++){
            for($j=0;$j<count($data[$i]);$j++){
                $value = $data[$i][$j];
                if ($value!==0 && empty($value)){
                    continue;
                }
                $sheet->setCellValueExplicitByColumnAndRow($j,$i+1,$value);
            }
        }
        //关掉自动计算列宽度。(性能)
        foreach ($sheet->getColumnDimensions() as $colDimension) {
            $colDimension->setAutoSize(false);
        }
        $objWriter = new PHPExcel_Writer_Excel2007($xls);
        $objWriter->save($filePath);
    }
    static function toOutput(ExcelData $excelData){
        $fileName = date('Y-m-d-H-i-s').'.xlsx';
        header("Content-type: application/vnd.ms-excel");
        header('Content-Disposition: attachment;filename="'.$fileName.'"');
        header('Cache-Control: max-age=0');
        self::toFile('php://output',$excelData);
        exit();
    }

    private static function Trim2DArray($input){
        if (empty($input)){
            return array();
        }
        $output = array();
        foreach($input as $row){
            $thisCell = self::TrimRightRowString($row);
            if (empty($thisCell)){
                continue;
            }
            $output[] = $thisCell;
        }
        return $output;
    }
    private static function TrimRightRowString($row){
        for($i=count($row)-1;$i>=0;$i--){
            $s = trim($row[$i]);
            if ($s!==''){
                return array_slice($row,0,$i+1);
            }
        }
        return array();
    }
}
